import json
from flask import current_app
import os

# print(os.path.dirname(__file__))
from pathlib import Path

file_name = Path(__file__).parent.parent.parent.joinpath('result.json')


class YuShuBook:
    books_info = json.load(open(file_name))

    @classmethod
    def search_by_isbn(cls, isbn):
        # 在books_info中查找到isbn匹配的书籍并返回
        for book in cls.books_info:
            if isbn == book.get('isbn'):
                return book
        return {}

    @classmethod
    def search_by_keyword(cls, keyword, page):
        # 在books_info中按名字匹配查找
        result = []
        count = current_app.config['PER_PAGE']

        for book in cls.books_info:
            title = book.get('title', '')
            subtitle = book.get('subtitle', '')
            summary = book.get('summary', '')
            if keyword in title or keyword in subtitle or keyword in summary:
                result.append(book)
        start = cls.calculate_start(page)
        books = result[start:start + count]
        res = {
            "books": books,
            "count": count,
            "start": start,
            "total": len(books)
        }
        return res

    @staticmethod
    def calculate_start(page):
        return (int(page) - 1) * current_app.config['PER_PAGE']


# class YuShuBook_V2:
#     isbn_url = 'http://t.yushu.im/v2/book/isbn/{}'
#     keyword_url = 'http://t.yushu.im/v2/book/search?q{}&count={}&start={}'
#
#     @classmethod
#     def search_by_isbn(cls, isbn):
#         url = cls.isbn_url.format(isbn)
#         result = MYHTTP.get(url)  # 返回字典dict
#         return result
#
#     @classmethod
#     def search_by_keyword(cls, keyword, count=15, start=0):
#         url = cls.keyword_url.format(keyword, count, start)
#         result = MYHTTP.get(url)
#         return result


if __name__ == '__main__':
    print(YuShuBook.search_by_isbn('9787544253994'))
    # print(YuShuBook.search_by_keyword('呐喊'))
